package net.maku.controller;

import java.io.ByteArrayOutputStream;
import java.util.Enumeration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import net.maku.bean.vo.WxPayResponeVo;
import net.maku.service.impl.BizTradeServiceImpl;
import net.maku.utils.MyRestTemplate;
import net.maku.utils.ReqUtils;



@Slf4j
@RestController
@RequestMapping 
@Tag(name="微信支付异步返回结果处理")
public class WeChatPayController {
	
	@RequestMapping(value = "/testimg1")
	public static String tpostData( ) {
		return MyRestTemplate.postData(1);
    }
	
	@RequestMapping(value = "/testimg2")
	public static String postData( ) {
		return MyRestTemplate.postData(2);
    }
	
	// 微信支付回调接口
	@RequestMapping(value = "/test")
	public String test() {
		ReqUtils.printAll();
		return "{\"code\": 200, \"analyes_ret\": \"根据您提供的照片，以下是一个相面分析的结果，作为模拟推演：\\n\\n1. **脸型**：从脸型来看，较为圆润，象征着温和与亲切。这种脸型的人通常待人友好，易于相处，能够获得他人的信任。\\n\\n2. **眉形**：眉毛稍微有些皱眉，显示出内心的紧张或烦恼，可能在情感上较敏感，容易受到外界环境影响，具有较强的观察力和同理心。\\n\\n3. **眼睛**：眼睛较大且有神，表明此人对事物充满好奇，聪慧灵动，能快速理解周围的环境与情感。\\n\\n4. **嘴型**：嘴巴微微撅起，显示出不满或失落。这种嘴型的人可能在表达情感时比较内向，常常隐藏自己的真实感受，不轻易向他人展示脆弱。\\n\\n综合分析，该个体可能是个性温和、敏感且善解人意的人，内心情感丰富，值得信赖。同时，因个性较为内向，建议多与他人沟通，以缓解内心的压力和焦虑。\", \"msg\": \"\"}";
	}
	
	
	
	/*
	// 微信支付回调接口
	@RequestMapping(value = "/notify")
	public String notify(HttpServletRequest request, HttpServletResponse response ) {
		try {
			ServletInputStream inStream = request.getInputStream();
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
	        byte[] buffer = new byte[10240];
	        int len = 0;
	        while ((len = inStream.read(buffer)) != -1) {
	            outSteam.write(buffer, 0, len);
	        }

	        // 获取微信调用我们notify_url的返回信息
	        String result = new String(outSteam.toByteArray(), "utf-8");
	        //WXPayUtil.getLogger().info("wxnotify:微信支付----result----=" + result);
	        System.out.println("------------------------start-----------------------------\n");
	        System.out.println(result);
	        log.info(result);
	        outSteam.close();
	        inStream.close();
	 
	        String signature = ReqUtils.getHeader(request, "Wechatpay-Signature", "" );
	        String timestamp = ReqUtils.getHeader(request, "Wechatpay-Timestamp", "" );
	        String signType  = ReqUtils.getHeader(request, "Wechatpay-Signature-Type", "" );
	        String serial    = ReqUtils.getHeader(request, "Wechatpay-Serial", "" );
	        String nonce     = ReqUtils.getHeader(request, "Wechatpay-Nonce", "" );

	        
			
			
	        String result = "{\"id\":\"4d519987-e3be-5c94-b55f-0b5f7017eaa3\",\"create_time\":\"2024-09-15T19:02:27+08:00\",\"resource_type\":\"encrypt-resource\",\"event_type\":\"TRANSACTION.SUCCESS\",\"summary\":\"支付成功\",\"resource\":{\"original_type\":\"transaction\",\"algorithm\":\"AEAD_AES_256_GCM\",\"ciphertext\":\"yWgNXQCOiUUN+WyIVLltkilvADGwl5hrKufPPf3v1csCRNFqEwm/x9nfBa7hQLSNwQJaKi/7O3O6J65pEg2L/iuuUObRdybKn5BSkotne6IQAe8dXQGEzLktpTNKzqoFq/FvwQyUxll1sEsEFxzl9uJHTB4xctYuuY4vu7bhK/JdKQVkHr7C8+Eqn8wJhAS4Ne9GupxyU1apQLymISbTHMdsF7+aF59kJoGL7h11CYlkKWXitIU614+DlUuaglNYmMchpNBmnrnCPXR1jETH37Tj830+rhU76Iw/BTr5DqDYdTlBpdEHOOB1QmRWxp52V0kWLsGUATEVTUBaZZZjKXXs+1+f0XeAu0EmWB1rYEnG08leaLAssSFOMJdqoVzVoql2uqvtBekdT/0g6/FmWtkC7LiG7wEr820gus5JomWhYfRLxmUiODzDFVPSzCVo5Cl3EpU8WyEb0M4DFULl67Hg/bjNPGjO9sxrBcxlgBtmxdC2Dixp3BHuQ2KJoAd9oTzuLkJXQtTPy7Y9YMXtzlf69J/Z3ESOY//WYbXume0fjoM8vhqmufO5uw+g0QUo\",\"associated_data\":\"transaction\",\"nonce\":\"4RIk6ppt5daM\"}}";
			String nonce = "dnd1FYqVdbykNObmKiWovZ9HPwjMCewU";
			String serial = "7BD20EE161296EF0F837D2B8A34E924047064E6B";
			String signature = "eoWH1LSqyN/OqIn9xHr1BQleWohwWzcP1sM2SM9ZssMxv4m6+DOfrzBaD3843CE7Bu+dJBebDJplggCGww3L2N72wrgJsNU/wJ6ltHDoA7j5XI94HLG1FGJ1gWqxASRTReek8wP2wya2F1/tOrn+1dOR89U3Lc4PbJ1fi+g4snQLIdd9aL7BaOFvhhonnKrFFr2z+AziyopfrDDdkfqouLi2MIZBPuLGrfri0pXeiBHDC/PXp2b79XQE/TnGK/lQgjnbuUumf1nTW6bRKW4ITDk35+AI1DAcRwPPypdEv6CyakTuuHnQwOgbOidEWbi4QirVhaxi0WbsF1o/0DkX0g==";
			String signType = "WECHATPAY2-SHA256-RSA2048";
			String timestamp = "1726398148";
			
			
	        System.out.println("------------------------header--------start---------------------\n");
	        System.out.println(signature);
	        System.out.println(timestamp);
	        System.out.println(signType);
	        System.out.println(serial);
	        System.out.println(nonce);
	        System.out.println("------------------------header--------end----------------------\n");
	        RequestParam requestParam = new RequestParam.Builder()
	                .serialNumber(serial)
	                .nonce(nonce)
	                .signature(signature)
	                .timestamp(timestamp)
	                .signType(signType)
	                .body(result)
	                .build();
	        Transaction transaction = notificationParser.parse(requestParam, Transaction.class);
	    	System.out.println( transaction.toString() );
	    	bizTradeServiceImpl.wxCallBackTrade(transaction.getOutTradeNo(), transaction.getTransactionId());
	    	System.out.println("------------------------end-----------------------------\n\n\n\n");
		} catch ( Exception e ) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


        Enumeration<String> headerNames = request.getHeaderNames();
        while(headerNames.hasMoreElements()){
            String element = headerNames.nextElement();
            System.out.println(element+":"+request.getHeader(element));
        }
        
     // 获取HTTP请求头中的 Wechatpay-Signature 、 Wechatpay-Nonce 、 Wechatpay-Timestamp 、 Wechatpay-Serial 、 Request-ID 、Wechatpay-Signature-Type 对应的值，构建 RequestParam 。
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(serial)
                .nonce(nonce)
                .signature(signature)
                .timestamp(timestamp)
                // 若未设置signType，默认值为 WECHATPAY2-SHA256-RSA2048
                .signType(signType)
                .body(result)
                .build();
 
        String apiV3key = "oXi4b7pE7YU5QRXCHC30tx5yfXJCAyyC";
        String merchantId = "1676811007";
        String privateKeyPath = "/home/jishu/bin/cert/apiclient_key.pem";
        //String privateKeyPath = "D:\\workspaces\\workspace202409\\duxinai-end\\cert\\apiclient_key.pem";

        String merchantSerialNumber = "3C8BB16E5EDCBDF6C814AC5276F239401AC401D3";
        
        RSAAutoCertificateConfig config = new RSAAutoCertificateConfig.Builder()
                .merchantId(merchantId)
                //.privateKey(wxPayConfig.getPrivateKey())
                .privateKeyFromPath(privateKeyPath)
                .merchantSerialNumber(merchantSerialNumber)
                .apiV3Key(apiV3key)
                .build();
 
        NotificationParser parser = new NotificationParser(config);
        Transaction transaction = parser.parse(requestParam, Transaction.class);
    	System.out.println( transaction.toString() );
    	System.out.println("------------------------end-----------------------------\n\n\n\n");
    	// {"amount":{"currency":"CNY","payer_currency":"CNY","payer_total":1,"total":1},"appid":"wx6ed1af0b9fdd0456","attach":"","bank_type":"OTHERS","mchid":"1676811007","out_trade_no":"rade_no_000000039","payer":{"openid":"oyiCY7ZI5zONxJ3f-O_eoV-N1naw"},"success_time":"2024-09-15T19:02:27+08:00","trade_state":"SUCCESS","trade_state_desc":"支付成功","trade_type":"JSAPI","transaction_id":"4200002367202409150770285274"}   
    	//transaction.getOutTradeNo()
    	//transaction.getTransactionId()
    	//bizTradeServiceImpl.wxCallBackTrade(transaction.getOutTradeNo(), transaction.getTransactionId());
    	
        
        
 
    	
 
        WxPayResponeVo vo = new  WxPayResponeVo();
   	 	vo.setCode("SUCCESS");
   	 	vo.setMessage("OK");
   	 	return vo.toString();
	}*/
	
	// 微信支付回调接口
	@RequestMapping(value = "/notify")
	public String notify(HttpServletRequest request, HttpServletResponse response ) {
		WxPayResponeVo vo = new  WxPayResponeVo();
		try {
		ServletInputStream inStream = request.getInputStream();
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }

        // 获取微信调用我们notify_url的返回信息
        String result = new String(outSteam.toByteArray(), "utf-8");
        //WXPayUtil.getLogger().info("wxnotify:微信支付----result----=" + result);
        System.out.println("------------------------start-----------------------------\n");
        System.out.println(result);
        log.info( "获取微信返回数据："+ result);
        outSteam.close();
        inStream.close();
 
        String signature = ReqUtils.getHeader(request, "Wechatpay-Signature", "" );
        String timestamp = ReqUtils.getHeader(request, "Wechatpay-Timestamp", "" );
        String signType  = ReqUtils.getHeader(request, "Wechatpay-Signature-Type", "" );
        String serial    = ReqUtils.getHeader(request, "Wechatpay-Serial", "" );
        String nonce     = ReqUtils.getHeader(request, "Wechatpay-Nonce", "" );

        System.out.println("------------------------header--------start---------------------\n");
        System.out.println(signature);
        System.out.println(timestamp);
        System.out.println(signType);
        System.out.println(serial);
        System.out.println(nonce);
        System.out.println("------------------------header--------end----------------------\n");
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(serial)
                .nonce(nonce)
                .signature(signature)
                .timestamp(timestamp)
                .signType(signType)
                .body(result)
                .build();
	        Transaction transaction = notificationParser.parse(requestParam, Transaction.class);
	    	System.out.println( transaction.toString() );
	    	bizTradeServiceImpl.wxCallBackTrade(transaction.getOutTradeNo(), transaction.getTransactionId());
	    	System.out.println("------------------------end-----------------------------\n\n\n\n");
		} catch ( Exception e ) {
			e.printStackTrace();
			log.info("微信支付回调失败： "+e.getMessage());
			vo.setCode("FAIL");
	   	 	vo.setMessage("处理失败");
	   	 	return vo.toString();
		}
		
		
   	 	vo.setCode("SUCCESS");
   	 	vo.setMessage("OK");
   	 	return vo.toString();
	}
 	

	@Autowired
	NotificationParser  notificationParser;
	
	@Autowired
    BizTradeServiceImpl bizTradeServiceImpl;

}



